//
//  ScanBinaryCodeViewController.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/3.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit
import AVFoundation
class ScanBinaryCodeViewController: BaseViewController,AVCaptureMetadataOutputObjectsDelegate {
    var scanObj : RJScanNative?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.naviHide = true
        self.view.backgroundColor = UIColor.white
        addOpaLayer()
        startScan()
        // Do any additional setup after loading the view.
    }
    
    func startScan() -> Void {
        let result = RJScanWrapper.isGetCameraPermission()
        if result == false {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: 1), execute: { 
                self.alertSomeMessage(title: YXAlertTitle, content: "请开启相机权限!", sureTitle: YXConfirmTitle, cancelTitle: YXCancelTitle, ensureAction: { (alert) in
                    UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!)
                }, cancelAction: { (alert) in
                    
                })
            })
            return
        }
        if scanObj == nil {
            weak var weakSelf = self
            let originX = 40 * YXWidthScale
            let wid = (YXDeviceWidth - 80 * YXWidthScale)
            
            let originY = (YXDeviceHeight - wid) / 2
            let rect = configInsterestRect(original: CGRect.init(x: originX, y: originY, width: wid, height: wid))
            scanObj = RJScanNative.init(preView: self.view, success: { (arr) in
                weakSelf!.scanResult(array: arr!)
            }, insterRect: rect)
        }
        scanObj!.startScan()
        
    }
    
    func scanResult(array : Array<RJScanResult>) -> Void {
        guard array.count > 0 else {
            return
        }
        scanObj!.stopScan()
        let result = array.first
        if result != nil {
            //url
            if let url = result?.strScanned {
                let bin = BinaryInfoViewController.init()
                bin.url = url
                self.navigationController?.pushViewController(bin, animated: true)
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        self.navigationController?.isNavigationBarHidden = false
    }
    
    func addOpaLayer() -> Void {
        let opaue = UIView.init()
        opaue.frame = self.view.bounds
        opaue.alpha = 0.5
        opaue.backgroundColor = UIColor.black
        self.view.addSubview(opaue)
        let back = UIButton.init(type: .system)
        back.frame = CGRect.init(origin: CGPoint.init(x: 30 * YXWidthScale, y: 60 * YXHeightScale), size: CGSize.init(width: YXWidthScale * 32, height: YXHeightScale * 32))
        back.tintColor = UIColor.white
        let image = UIImage.load(name: "nav_scan_close")
        back.setImage(image, for: .normal)
        back.addTarget(self, action: #selector(pop), for: .touchUpInside)
        opaue.addSubview(back)
        let label = UILabel.init()
        let font = UIFont.systemFont(ofSize: 28 * YXWidthScale)
        let size = "二维码/条形码放入框内".StringSize(font: font)
        label.frame = CGRect.init(x: YXDeviceWidth / 2 - size.width / 2, y: YXDeviceHeight / 2 + YXDeviceWidth / 2 + 40 * YXHeightScale, width: size.width, height: 2 * size.height)
        label.textAlignment = .center
        label.textColor = UIColor.white
        label.numberOfLines = 2
        label.text = "二维码/条形码放入框内自动扫描"
        label.font = font
        opaue.addSubview(label)
        
        let shape = CAShapeLayer.init()
        let path = UIBezierPath.init(rect: self.view.bounds)
        let originX = 40 * YXWidthScale 
        let wid = (YXDeviceWidth - 80 * YXWidthScale)
        
        let originY = (YXDeviceHeight - wid) / 2
        
        let p = UIBezierPath.init(rect: CGRect.init(origin: CGPoint.init(x: originX, y: originY), size: CGSize.init(width: wid, height: wid)))
        let scan = Scan.init(frame: CGRect.init(origin: CGPoint.init(x: originX, y: originY), size: CGSize.init(width: wid, height: wid)))
        self.view.addSubview(scan)
        scan.startScan()
        path.append(p.reversing())
        shape.path = path.cgPath
        shape.fillColor = UIColor.red.cgColor
        opaue.layer.mask = shape
    }
    
    func configInsterestRect(original : CGRect) -> CGRect {
        let size = self.view.bounds.size;
        let p1 = size.height / size.width
        let p2 = CGFloat(1920.0) / CGFloat(1080.0)
        if p1 < p2 {
            let fixHeight = size.width * 1920.0 / 1080.0
            let fixPadding = (fixHeight - size.height) / 2
            return CGRect.init(x: (original.origin.y + fixPadding)/fixHeight, y: original.origin.x/size.width, width: original.size.height / fixHeight, height: original.size.width / size.width)
        }else{
            let fixWidth = self.view.bounds.size.height * 1080.0 / 1920.0;
            let fixPadding = (fixWidth - size.width) / 2;
            return CGRect.init(x: original.origin.y / size.height, y: (original.origin.x + fixPadding) / fixWidth, width: original.size.height / size.height, height: original.size.width / fixWidth)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
